package com.cnspt.utils;

import com.itextpdf.text.*;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.List;
import java.util.Map;

public class Pdf {
    /**
     * 生成新的PDF
     * @param String pdfPath 要编辑的PDF路径
     * @param String newPDFPath 生成新的PDF路径
     * @param String pdfHeight pdf高
     * @param String pdfWidth pdf宽
     * @param List signs 签章数据
     * @param String password 文档加密，密码为空时不加密
     * @param String sealSign 是否盖骑缝章
     */
    public static void generatePDF(String pdfPath, String newPDFPath, String pdfHeight, String pdfWidth, List signs, String password, String sealSign) {
        try {
            //创建一个pdf读入流
            InputStream input = new FileInputStream(new File(pdfPath));
            PdfReader reader = new PdfReader(input);
            Rectangle pageSize = reader.getPageSize(1);
            float height = pageSize.getHeight();
            float width = pageSize.getWidth();
            //根据一个pdfreader创建一个pdfStamper.用来生成新的pdf.
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(newPDFPath));

            //判断文档是否需要加密
            if(password.length() != 0) {
                // 设置用户密码, 所有者密码,用户权限,所有者权限
                stamper.setEncryption(password.getBytes(), password.getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
            }

            PdfContentByte over;

            int pages = reader.getNumberOfPages();

            //获取分割后的印章图片
            Image[] images = GetImage(sealSign ,pages);
            //页数是从1开始的
            for (int i = 1; i <= pages; i++) {
                //获得pdfstamper在当前页的上层打印内容.也就是说 这些内容会覆盖在原先的pdf内容之上.
                over = stamper.getOverContent(i);
                //用pdfreader获得当前页字典对象.包含了该页的一些数据.比如该页的坐标轴信息.
                PdfDictionary p = reader.getPageN(i);
                //拿到mediaBox 里面放着该页pdf的大小信息.
                PdfObject po = p.get(new PdfName("MediaBox"));
                //po是一个数组对象.里面包含了该页pdf的坐标轴范围.
                PdfArray pa = (PdfArray) po;

                //pdf盖章
                for(int j = 0;j < signs.size();j++)
                {
                    Map sign = (Map) signs.get(j);
                    String pageNum = sign.get("pageNum").toString();
                    if(i == Integer.valueOf(pageNum).intValue()) {
                        String top = sign.get("top").toString();
                        String left = sign.get("left").toString();
                        String sighWidth = sign.get("width").toString();
                        String sighHeight = sign.get("height").toString();
                        String sealUrl = sign.get("sealUrl").toString();
                        //创建一个image对象.
                        Image image = Image.getInstance(sealUrl);
                        //设置插入的图片大小
                        if(sighWidth.equals(sighHeight)) {
                            image.setAbsolutePosition(Float.parseFloat(left), Float.parseFloat(pdfHeight)-Float.parseFloat(top)-120);
                            image.scaleToFit(118, 118);
                        }else{
                            image.setAbsolutePosition(Float.parseFloat(left), Float.parseFloat(pdfHeight)-Float.parseFloat(top)-40);
                            image.scaleToFit(100, 30);
                        }

                        over.addImage(image);
                    }
                }

                //处理骑缝章
                if(sealSign.length() != 0) {
                    Image img= images[ i-1 ];
                    float ratio = img.getHeight()/118;
                    if(pages < 15) { //如果总页数小于15
                        img.setAbsolutePosition(width-img.getWidth()/ratio,height/2-img.getHeight()/2);//控制图片位置
                        float widthImg = 118/pages;
                        img.scaleToFit(widthImg, 118);
                    } else { //如果总页数大于等于15
                        img.setAbsolutePosition(width-img.getWidth()/ratio,height/2-img.getHeight()/2);//控制图片位置
                        img.scaleToFit(20, 118);
                    }
                    over.addImage(img);
                }
            }
            stamper.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static Image[] GetImage(String path, int num) throws IOException, BadElementException {
        Image[] imgs = new Image[ num ];

        if(path.length() == 0) return imgs;

        URL url = new URL(path);
        BufferedImage image = ImageIO.read(url);

        ByteArrayOutputStream out = new ByteArrayOutputStream();


        int h = image.getHeight();
        int w = image.getWidth();

        int remainder = num % 15;
        int quotients = num / 15;

        int sw;
        int n = 0;
        for (int i = 0; i < num; i++) {
            BufferedImage subImg;
            if(num < 15) { //如果总页数小于15
                sw = w / num;
                if(i == num-1){//最后剩余部分
                    subImg = image.getSubimage(n * sw, 0, w-n*sw, h);
                } else {//前n-1块均匀切
                    subImg = image.getSubimage(n * sw, 0, sw, h);
                }
            } else { //如果总页数大于等于15
                if(remainder == 0) { //如果被整除
                    if(i % 15 == 0) {
                        n = 0;
                    }
                    sw = w / 15;
                    if(n == 14){//最后剩余部分
                        subImg = image.getSubimage(n * sw, 0, w-n*sw, h);
                    } else {//前n-1块均匀切
                        subImg = image.getSubimage(n * sw, 0, sw, h);
                    }
                } else { //如果不被整除
                    sw = w / 15;
                    if(remainder > 9) { //如果余数大于9
                        if( i >= quotients * 15 ) {
                            if( i == quotients * 15 ) n = 0;
                            sw = w / remainder;
                            if(n == (remainder - 1)){//最后剩余部分
                                subImg = image.getSubimage(n * sw, 0, w-n*sw, h);
                            } else {//前n-1块均匀切
                                subImg = image.getSubimage(n * sw, 0, sw, h);
                            }
                        }else{
                            if(i % 15 == 0) {
                                n = 0;
                            }
                            if(n == 14){//最后剩余部分
                                subImg = image.getSubimage(n * sw, 0, w-n*sw, h);
                            } else {//前n-1块均匀切
                                subImg = image.getSubimage(n * sw, 0, sw, h);
                            }
                        }
                    } else { //如果余数小于等于9
                        if( i >= (quotients - 1) * 15 ) {
                            if( i == (quotients - 1) * 15 ) n = 0;
                            sw = w / (15 + remainder);
                            if(n == (15 + remainder - 1)){//最后剩余部分
                                subImg = image.getSubimage(n * sw, 0, w-n*sw, h);
                            } else {//前n-1块均匀切
                                subImg = image.getSubimage(n * sw, 0, sw, h);
                            }
                        }else{
                            if(i % 15 == 0) {
                                n = 0;
                            }
                            sw = w / 15;
                            if(n == 14){//最后剩余部分
                                subImg = image.getSubimage(n * sw, 0, w-n*sw, h);
                            } else {//前n-1块均匀切
                                subImg = image.getSubimage(n * sw, 0, sw, h);
                            }
                        }
                    }
                }
            }
            n++;
            ImageIO.write(subImg,path.substring(path.lastIndexOf('.')+1),out);
            imgs[i] = Image.getInstance(out.toByteArray());
            out.flush();
            out.reset();
        }
        return imgs;
    }
}